package com.gxzy.util.convert;

import com.gxzy.config.FinalPoolCfg;
import com.gxzy.util.encryption.AESUtil;
import com.gxzy.util.encryption.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.AttributeConverter;

/**
 * AttributeConverter: 此接口用于转化实体属性的
 * 用于对隐私信息进行加解密
 */

public class SensitiveInfoEncryptionConvert implements AttributeConverter<String, String> {
    private static Logger log = LoggerFactory.getLogger(SensitiveInfoEncryptionConvert.class);

    @Override
    public String convertToDatabaseColumn(String value) {
        return passwordEncrypt(value, true);
    }

    @Override
    public String convertToEntityAttribute(String value) {
        return passwordEncrypt(value, false);
    }

    /**
     * 加解密
     *
     * @param value
     * @param encrypt
     * @return
     */
    public static String passwordEncrypt(String value, boolean encrypt) {
        try {
            if (value == null || value.length() == 0) {
                return value;
            }

            if (encrypt) {
                return AESUtil.encrypt(value, FinalPoolCfg.SECRET_KEY);
            } else {
                return AESUtil.decrypt(value, FinalPoolCfg.SECRET_KEY);
            }
        } catch (Exception e) {
            log.error("密码:" + value + ",加密失败", e);
        }
        return null;
    }
}
